<template>
  <view class="address-edit-container">
    <!-- 头部导航 -->
    <view class="header">
      <!-- <text class="back-btn" @click="goBack">←</text> -->
      <text class="title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
      <text class="save-btn" @click="saveAddress">保存</text>
    </view>
    
    <!-- 表单区域 -->
    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" v-model="form.name" placeholder="请输入收货人姓名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" v-model="form.phone" type="number" placeholder="请输入手机号码" />
      </view>
      
      <!-- 省市区选择 -->
      <view class="form-item">
        <text class="label">所在地区</text>
        <view class="region-row">
          <picker mode="selector" :range="provinceList" range-key="name" @change="onProvinceChange">
            <view class="region-item" :class="{placeholder: !form.province}">
              {{ form.province || '省' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
          <picker mode="selector" :range="cityList" range-key="name" @change="onCityChange" :disabled="!form.province">
            <view class="region-item" :class="{placeholder: !form.city, disabled: !form.province}">
              {{ form.city || '市' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
          <picker mode="selector" :range="districtList" range-key="name" @change="onDistrictChange" :disabled="!form.city">
            <view class="region-item" :class="{placeholder: !form.district, disabled: !form.city}">
              {{ form.district || '区/县' }}
              <text class="arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea class="textarea" v-model="form.detailAddress" placeholder="请输入街道、楼栋号、门牌号等" auto-height />
      </view>
      
      <!-- <view class="form-item">
        <text class="label">设为默认地址</text>
        <switch :checked="form.isDefault" @change="(e) => form.isDefault = e.detail.value" color="#007AFF" />
      </view> -->
    </view>
    
    <!-- 删除按钮（编辑模式下显示） -->
    <!-- <button class="delete-btn" @click="deleteAddress" v-if="isEdit">删除地址</button> -->
  </view>
</template>

<script>
import provinces from '/src/region-data.js';

export default {
  data() {
    return {
      isEdit: false,
      editId: null, // 编辑的地址ID
      form: {
        id: '',
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        detailAddress: '',
        isDefault: false
      },
      provinceList: [],
      cityList: [],
      districtList: []
    };
  },
  onLoad(options) {
    this.provinceList = provinces;
    
    if (options.edit === 'true') {
      this.isEdit = true;
      this.editId = options.id;
      
      // 初始化表单数据
      this.form = {
        id: options.id,
        name: options.name || '',
        phone: options.phone || '',
        province: options.province || '',
        city: options.city || '',
        district: options.district || '',
        detailAddress: options.detailAddress || '',
        isDefault: options.isDefault === 'true'
      };

      // 加载对应的城市和区县数据
      if (this.form.province) {
        const selectedProvince = this.provinceList.find(p => p.name === this.form.province);
        if (selectedProvince) {
          this.cityList = selectedProvince.children || [];
          
          if (this.form.city) {
            const selectedCity = this.cityList.find(c => c.name === this.form.city);
            if (selectedCity) {
              this.districtList = selectedCity.children || [];
            }
          }
        }
      }
    }
  },
  methods: {
    goBack() {
      uni.navigateBack();
    },
    
    onProvinceChange(e) {
      const index = e.detail.value;
      this.form.province = this.provinceList[index].name;
      this.form.city = '';
      this.form.district = '';
      this.cityList = this.provinceList[index].children || [];
      this.districtList = [];
    },
    
    onCityChange(e) {
      const index = e.detail.value;
      this.form.city = this.cityList[index].name;
      this.form.district = '';
      this.districtList = this.cityList[index].children || [];
    },
    
    onDistrictChange(e) {
      const index = e.detail.value;
      this.form.district = this.districtList[index].name;
    },
    
    validateForm() {
      if (!this.form.name.trim()) {
        uni.showToast({ title: '请输入收货人姓名', icon: 'none' });
        return false;
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
        uni.showToast({ title: '请输入正确的手机号码', icon: 'none' });
        return false;
      }
      
      if (!this.form.province || !this.form.city || !this.form.district) {
        uni.showToast({ title: '请选择完整的地区信息', icon: 'none' });
        return false;
      }
      
      if (!this.form.detailAddress.trim()) {
        uni.showToast({ title: '请输入详细地址', icon: 'none' });
        return false;
      }
      
      return true;
    },
    
    saveAddress() {
      if (!this.validateForm()) return;
      
      let addressList = uni.getStorageSync('addressList') || [];
      
      if (this.isEdit) {
        // 编辑模式：更新现有地址
        const index = addressList.findIndex(item => item.id === this.editId);
        if (index !== -1) {
          addressList[index] = { ...this.form };
        }
      } else {
        // 新增模式：添加新地址
        this.form.id = Date.now().toString();
        addressList.push({ ...this.form });
      }
      
      // 如果设为默认地址，取消其他默认地址
      if (this.form.isDefault) {
        addressList.forEach(item => {
          if (item.id !== this.form.id) {
            item.isDefault = false;
          }
        });
      }
      
      uni.setStorageSync('addressList', addressList);
      
      uni.showToast({
        title: '保存成功',
        icon: 'success',
        success: () => {
          setTimeout(() => {
            uni.navigateBack();
            // 如果需要刷新前页数据，可以触发事件
            uni.$emit('addressUpdated');
          }, 1500);
        }
      });
    },
    
    deleteAddress() {
      uni.showModal({
        title: '提示',
        content: '确定要删除这个地址吗？',
        success: (res) => {
          if (res.confirm) {
            let addressList = uni.getStorageSync('addressList') || [];
            addressList = addressList.filter(item => item.id !== this.editId);
            uni.setStorageSync('addressList', addressList);
            
            uni.showToast({
              title: '删除成功',
              icon: 'success',
              success: () => {
                setTimeout(() => {
                  uni.navigateBack();
                  uni.$emit('addressUpdated');
                }, 1500);
              }
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.address-edit-container {
  padding: 15px;
  background-color: #f9f9f9;
  min-height: 100vh;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background-color: white;
  margin-bottom: 15px;
  position: relative;
}

.back-btn {
  font-size: 20px;
  color: #333;
}

.title {
  font-size: 16px;
  font-weight: bold;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.save-btn {
  font-size: 16px;
  color: #007AFF;
  font-weight: 500;
}

.form-container {
  background-color: white;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
}

.form-item {
  margin-bottom: 20px;
}

.label {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  display: block;
  font-weight: 500;
}

.input, .textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  font-size: 14px;
}

.textarea {
  min-height: 80px;
}

.region-row {
  display: flex;
  justify-content: space-between;
}

.region-item {
  flex: 1;
  margin-right: 8px;
  padding: 10px;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  font-size: 14px;
  display: flex;
  justify-content: space-between;
}

.region-item:last-child {
  margin-right: 0;
}

.placeholder {
  color: #999;
}

.disabled {
  background-color: #f5f5f5;
  color: #ccc;
}

.arrow {
  font-size: 12px;
  color: #666;
}

.delete-btn {
  width: 100%;
  background-color: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 12px;
  font-size: 16px;
  margin-top: 20px;
}
</style>